package com.leessy.r229.server.http;/*
 * Copyright (C) 2017 zhouyou(478319399@qq.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import android.util.Base64;
import android.util.Log;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.leessy.r229.server.HttpApi;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;


/**
 * @author : Created by liucheng. on 2021/01/19
 * @description : 加密处理
 */
public class DecryptInterceptor implements Interceptor {
    private static final String TAG = "DecryptInterceptor";
    private MediaType mediaType = MediaType.parse("application/json");

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        // 拿到请求参数
        Request request = chain.request();
        String method = request.method();
        Response response = chain.proceed(request);
        if (/*isEncrypt(url) &&*/ method.equals("POST")) {
            //对响应进行解密
            ResponseBody responseBody = response.body();
            byte[] contents = responseBody.bytes();
            byte[] decode = Base64.decode(contents, Base64.NO_WRAP);
            byte[] keys = ConvertUtils.hexString2Bytes("e4e3e1ef9ee249328c4a1b6a0293c4dae4e3e1ef9ee24932");
            byte[] enrypt = EncryptUtils.decrypt3DES(
                    decode,
                    keys,
                    "DESede/ECB/NoPadding",
                    null
            );
            if (enrypt == null) return response;
            ResponseBody newResponseBody = ResponseBody.create(mediaType, getStrGbk(enrypt));
            return response.newBuilder().body(newResponseBody).build();
        }
        return response;
    }

    String getStrGbk(byte[] bytes) {
        int r = 0;
        for (int i = 1; i < 8; i++) {
            if (bytes[bytes.length - i] != 0) break;
            else r++;
        }
        try {
            return new String(bytes, 0, bytes.length - r, "gbk");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

}



